#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include <memory>  // 用于智能指针

namespace ThreadModule
{
    template<typename T>
    using func_t = std::function<void(T)>;

    template<typename T>
    class Thread
    {
    private:
        pthread_t _tid;
        std::string _threadname;
        func_t<T> _func;
        bool _stop;
        T _data;
    public:
        Thread(func_t<T> func, T& data, const std::string& threadname = "default name")
            : _func(func), _data(data), _threadname(threadname), _stop(true) {}

        ~Thread() {}

        void Execute()
        {
            _func(_data);
        }

        static void* threadroutine(void* args)
        {
            Thread* self = static_cast<Thread*>(args);
            self->Execute();
            return nullptr;
        }

        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadroutine, this);
            if (n == 0)
            {
                _stop = false;
                return true;
            }
            else
            {
                return false;
            }
        }

        void Detach()
        {
            if (!_stop)
            {
                pthread_detach(_tid);
            }
        }

        void Join()
        {
            if (!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }

        void Stop()
        {
            _stop = true;
        }
    };
}